package library_system.com;

import library_system.Util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

/**
 * @author haomin
 * @date 2022/04/05 20:09
 **/
public class PutOffCommand {
    public static void main(String[] args) throws SQLException {
        // 1. 不需要的登录
        // 2. 读取用户输入
        Scanner scanner = new Scanner(System.in);
        System.out.print("请输入书名: ");
        String name = scanner.nextLine();
        System.out.print("请输入本次上架的书籍数量: ");
        int count = scanner.nextInt();

        System.out.println("DEBUG: 读取到用户输入的书名是 |" + name + "|");
        System.out.println("DEBUG: 读取到用户输入的数量是 |" + count + "|");

        // 3. sql
        // 3.1 select
        // 根据用户输入 和 总量的关系，决定是 delete 还是 update
        Integer bid = null;
        Integer bookCount = null;
        Integer total = null;
        try(Connection c = DBUtil.connection()){
            String sql = "select bid ,stock ,total from books where name = ?";
            try (PreparedStatement ps = c.prepareStatement(sql)){
                ps.setString(1,name);

                System.out.println("DEBUG:执行 SQL：" + ps);

                try(ResultSet rs = ps.executeQuery()){
                    if(rs.next()){
                        bid = rs.getInt("bid");
                        bookCount = rs.getInt("stock");
                        total = rs.getInt("total");
                    }
                }
            }
        }
        System.out.println("DEBUG: 根据书名查询到的 bid = " + bid);
        System.out.println("DEBUG: 根据书名查询到的 bookCount = " + bookCount);
        System.out.println("DEBUG: 根据书名查询到的 total = " + total);

        if(bid == null){
            System.out.println("没有此书！");
            return;
        }

        if(count >= total){
            // delete
            System.out.println("DEBUG: 使用 delete 下架");
            try (Connection c = DBUtil.connection()) {
                String sql = "delete from books where bid = ?";
                try (PreparedStatement ps = c.prepareStatement(sql)) {
                    ps.setInt(1, bid);

                    System.out.println("DEBUG: 执行 SQL: " + ps);

                    ps.executeUpdate();
                }
            }
        }else {
            // update
            System.out.println("DEBUG: 使用 update 下架");
            try(Connection c = DBUtil.connection()){
                String sql = "update books set stock = stock - ? ,total = total - ? where bid = ?";
                // TODO: 存在一个 BUG，书籍的存量可能会出现负数
                try(PreparedStatement ps = c.prepareStatement(sql)){
                    ps.setInt(1, count);
                    ps.setInt(2, count);
                    ps.setInt(3, bid);

                    System.out.println("DEBUG: 执行 SQL: " + ps);

                    ps.executeUpdate();
                }
            }
        }
        System.out.println("下架成功！");
    }
}